<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,NIO," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="多数情况下，通道与操作系统的文件描述符合文件句柄有着一对一的关系。通常用到的多数通道都是连接到开放的文件描述符。 通道是一种途径，借助该途径，可以用最小的总开销来访问操作系统本身的I/O服务。 不同操作系统之间通道channel的实现有根本性的差异，Channel接口的实现经常使用操作系统的本地代码。 因为操作系统都是以字节的形式实现底层I/O接口，所以通道只能在字节缓冲区上操作。其他类型的通道">
<meta name="keywords" content="java,NIO">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaNIO之三：通道Channel">
<meta property="og:url" content="https://gitee.com/shuhao/2018/05/09/JavaNIO之三：通道Channel/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="多数情况下，通道与操作系统的文件描述符合文件句柄有着一对一的关系。通常用到的多数通道都是连接到开放的文件描述符。 通道是一种途径，借助该途径，可以用最小的总开销来访问操作系统本身的I/O服务。 不同操作系统之间通道channel的实现有根本性的差异，Channel接口的实现经常使用操作系统的本地代码。 因为操作系统都是以字节的形式实现底层I/O接口，所以通道只能在字节缓冲区上操作。其他类型的通道">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-28T01:28:18.006Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaNIO之三：通道Channel">
<meta name="twitter:description" content="多数情况下，通道与操作系统的文件描述符合文件句柄有着一对一的关系。通常用到的多数通道都是连接到开放的文件描述符。 通道是一种途径，借助该途径，可以用最小的总开销来访问操作系统本身的I/O服务。 不同操作系统之间通道channel的实现有根本性的差异，Channel接口的实现经常使用操作系统的本地代码。 因为操作系统都是以字节的形式实现底层I/O接口，所以通道只能在字节缓冲区上操作。其他类型的通道">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/05/09/JavaNIO之三：通道Channel/"/>





  <title> JavaNIO之三：通道Channel | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/05/09/JavaNIO之三：通道Channel/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JavaNIO之三：通道Channel
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-09T08:28:19+08:00">
                2018-05-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <ol>
<li>多数情况下，通道与操作系统的文件描述符合文件句柄有着一对一的关系。通常用到的多数通道都是连接到开放的文件描述符。</li>
<li>通道是一种途径，借助该途径，可以用最小的总开销来访问操作系统本身的I/O服务。</li>
<li>不同操作系统之间通道channel的实现有根本性的差异，Channel接口的实现经常使用操作系统的本地代码。</li>
<li>因为操作系统都是以字节的形式实现底层I/O接口，所以通道只能在字节缓冲区上操作。其他类型的通道则需要将数据结构与字节数据进行转换。</li>
<li>因为I/O主要分为两大类：<strong>File I/O 和 Stream I/O</strong>，所以通道也相应的分为两大类。</li>
<li>Channel主要对象为：文件类型的通道：FileChannel；流类型通道：SocketChannel、ServerSocketChannel和DatagramChannel</li>
<li>通道可以通过<strong>阻塞</strong>和<strong>非阻塞</strong>的方式运行。非阻塞模式不会让线程休眠，操作要么立即完成，要么返回一个结果表明为进行任何操作。只有面向流的通道才使用非阻塞模式。因为通道有非阻塞的方式，因此可以合选择器（selectors）一起使用，组成<strong>多路复用I/O模型</strong>，提高系统IO的效率。</li>
<li>通道不可重复利用，关闭后，通道的连接也丢失。</li>
</ol>
<h2 id="文件通道"><a href="#文件通道" class="headerlink" title="文件通道"></a>文件通道</h2><ol>
<li>文件通道自1.4以后实现了文件锁，但是锁的实现基于本地操作系统以及文件系统(并不是所有的操作系统都支持文件锁)。且该<strong>文件锁是在进程级别，而不是线程级别。</strong>例如。一个JVM的线程打开一个FileChannel申请到一个文件的锁，而该JVM中的另一个线程再通过打开一个FileChannel去申请该文件的锁，会被批准；然而，另外一个JVM进程中的某个线程去申请该文件的锁就会被拒绝。并且<strong>文件锁是与一个文件关联的，而不是与单个文件句柄或者通道关联</strong></li>
</ol>
<ol>
<li>而java也提供了为线程获得独占锁的解决方案，就是在FileChannel类内部实现了一个lock，该锁可以锁定文件的任何区域（可对文件区域加锁），且可以设置为是否为共享锁（必须获取读权限）或独占锁（必须获取写权限）。加锁后，当前线程必须等待前面的锁被释放后才允许访问该文件。</li>
</ol>
<p>下面是FileChannel实现线程级别的文件锁的一些源码<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">FileChannel</span> <span class="keyword">extends</span> <span class="title">AbstractInterruptibleChannel</span> <span class="keyword">implements</span> <span class="title">SeekableByteChannel</span>, <span class="title">GatheringByteChannel</span>, <span class="title">ScatteringByteChannel</span></span>&#123;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> FileLock <span class="title">lock</span><span class="params">(<span class="keyword">long</span> position, <span class="keyword">long</span> size, <span class="keyword">boolean</span> shared)</span> <span class="keyword">throws</span> IOException</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> FileLock <span class="title">lock</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> lock(<span class="number">0L</span>, Long.MAX_VALUE, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> FileLock <span class="title">tryLock</span><span class="params">(<span class="keyword">long</span> position, <span class="keyword">long</span> size, <span class="keyword">boolean</span> shared)</span> <span class="keyword">throws</span> IOException</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> FileLock <span class="title">tryLock</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> tryLock(<span class="number">0L</span>, Long.MAX_VALUE, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">FileLock</span> <span class="keyword">implements</span> <span class="title">AutoCloseable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Channel channel;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">long</span> position;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">long</span> size;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> shared;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="title">FileLock</span><span class="params">(FileChannel channel,</span></span></span><br><span class="line"><span class="function"><span class="params">                       <span class="keyword">long</span> position, <span class="keyword">long</span> size, <span class="keyword">boolean</span> shared)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (position &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative position"</span>);</span><br><span class="line">        <span class="keyword">if</span> (size &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative size"</span>);</span><br><span class="line">        <span class="keyword">if</span> (position + size &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative position + size"</span>);</span><br><span class="line">        <span class="keyword">this</span>.channel = channel;</span><br><span class="line">        <span class="keyword">this</span>.position = position;</span><br><span class="line">        <span class="keyword">this</span>.size = size;</span><br><span class="line">        <span class="keyword">this</span>.shared = shared;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="title">FileLock</span><span class="params">(AsynchronousFileChannel channel,</span></span></span><br><span class="line"><span class="function"><span class="params">                       <span class="keyword">long</span> position, <span class="keyword">long</span> size, <span class="keyword">boolean</span> shared)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (position &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative position"</span>);</span><br><span class="line">        <span class="keyword">if</span> (size &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative size"</span>);</span><br><span class="line">        <span class="keyword">if</span> (position + size &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative position + size"</span>);</span><br><span class="line">        <span class="keyword">this</span>.channel = channel;</span><br><span class="line">        <span class="keyword">this</span>.position = position;</span><br><span class="line">        <span class="keyword">this</span>.size = size;</span><br><span class="line">        <span class="keyword">this</span>.shared = shared;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">overlaps</span><span class="params">(<span class="keyword">long</span> position, <span class="keyword">long</span> size)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (position + size &lt;= <span class="keyword">this</span>.position)</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;               <span class="comment">// That is below this</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.position + <span class="keyword">this</span>.size &lt;= position)</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;               <span class="comment">// This is below that</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意在获得FileLock时，并不一定都能获得锁，因为必能保证该文件的进程级别的锁被其他程序或其他JVM进程所持有。因此可以调用tryLock方法确认是否可以获得锁。<br>然后需要注意的是，获得锁之后必须要及时释放，因为FileLock锁代表的锁和底层文件相关，如果不及时释放，则可能导致其他程序无法访问该文件。</p>
<h2 id="内存映射文件"><a href="#内存映射文件" class="headerlink" title="内存映射文件"></a>内存映射文件</h2><h4 id="什么是内存映射文件"><a href="#什么是内存映射文件" class="headerlink" title="什么是内存映射文件"></a>什么是内存映射文件</h4><h4 id="为什么使用内存映射文件"><a href="#为什么使用内存映射文件" class="headerlink" title="为什么使用内存映射文件"></a>为什么使用内存映射文件</h4><ul>
<li>使用内存映射访问文件比常规访问文件的效率高得多，甚至比Channel访问文件的效率都高。</li>
</ul>
<ol>
<li>因为访问内存映射文件不需要做系统调用</li>
<li>操作系统的虚拟内存可以自动缓存内存页，这些内存页属于系统内存，不属于JVM进程中的内存，因此不会有堆上的创建和回收的性能消耗。</li>
</ol>
<h4 id="如何使用内存映射文件"><a href="#如何使用内存映射文件" class="headerlink" title="如何使用内存映射文件"></a>如何使用内存映射文件</h4><p>在FileChannel上调用map方法会创建一个由磁盘文件支持的虚拟内存映射，并在该快虚拟内存空间外部封装一个MappedByByteBuffer对象<br>我们看下FileChannel类中对map方法的定义<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> MappedByteBuffer <span class="title">map</span><span class="params">(MapMode mode, <span class="keyword">long</span> position, <span class="keyword">long</span> size)</span> <span class="keyword">throws</span> IOException</span>;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>该方法是<strong>唯一</strong>创建一个文件映射的方法。他参数position,size同lock方法的两个参数一样，用来创建一个MappedByteBuffer来代表一个文件中字节的某个子范围。并且该范围不应超过整个文件的范围（文件锁可以大于文件的范围）。因为超过的话，文件会增大已匹配映射的大小。</li>
<li>MapMode的模式</li>
</ul>
<ol>
<li>MapMode.READ_ONLY</li>
<li>MapMode.READ_WRITE</li>
<li>MapMode.PRIVATE<br>前两种模式很明显，表示你希望映射的文件的读写权限，但是该读写权限依赖于文件FileChannel的权限。如果FileChannel只有读权限，申请MappedByteBuffer的权限READ_WRITE的话，则会抛出NonWriteableChannelException。第三个权限表示写拷贝映射，表示通过put()方法对文件的改变，只在本MappedByteBuffer中可见，不会修改底层文件。</li>
</ol>
<p>该方法在FileChannelImpl实现类中实现<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> MappedByteBuffer <span class="title">map</span><span class="params">(MapMode var1, <span class="keyword">long</span> var2, <span class="keyword">long</span> var4)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.ensureOpen();</span><br><span class="line">    <span class="keyword">if</span> (var1 == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException(<span class="string">"Mode is null"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var2 &lt; <span class="number">0L</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative position"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var4 &lt; <span class="number">0L</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Negative size"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var2 + var4 &lt; <span class="number">0L</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Position + size overflow"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var4 &gt; <span class="number">2147483647L</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Size exceeds Integer.MAX_VALUE"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">byte</span> var6 = -<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (var1 == MapMode.READ_ONLY) &#123;</span><br><span class="line">            var6 = <span class="number">0</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var1 == MapMode.READ_WRITE) &#123;</span><br><span class="line">            var6 = <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (var1 == MapMode.PRIVATE) &#123;</span><br><span class="line">            var6 = <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">assert</span> var6 &gt;= <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (var1 != MapMode.READ_ONLY &amp;&amp; !<span class="keyword">this</span>.writable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NonWritableChannelException();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!<span class="keyword">this</span>.readable) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NonReadableChannelException();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">long</span> var7 = -<span class="number">1L</span>;</span><br><span class="line">            <span class="keyword">int</span> var9 = -<span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">            MappedByteBuffer var13;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.begin();</span><br><span class="line">                var9 = <span class="keyword">this</span>.threads.add();</span><br><span class="line">                <span class="keyword">if</span> (!<span class="keyword">this</span>.isOpen()) &#123;</span><br><span class="line">                    Object var32 = <span class="keyword">null</span>;</span><br><span class="line">                    <span class="keyword">return</span> (MappedByteBuffer)var32;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">long</span> var10;</span><br><span class="line">                <span class="keyword">do</span> &#123;</span><br><span class="line">                    var10 = <span class="keyword">this</span>.nd.size(<span class="keyword">this</span>.fd);</span><br><span class="line">                &#125; <span class="keyword">while</span>(var10 == -<span class="number">3L</span> &amp;&amp; <span class="keyword">this</span>.isOpen());</span><br><span class="line"></span><br><span class="line">                FileDescriptor var33;</span><br><span class="line">                <span class="keyword">if</span> (!<span class="keyword">this</span>.isOpen()) &#123;</span><br><span class="line">                    var33 = <span class="keyword">null</span>;</span><br><span class="line">                    <span class="keyword">return</span> var33;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">int</span> var12;</span><br><span class="line">                <span class="keyword">if</span> (var10 &lt; var2 + var4) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (!<span class="keyword">this</span>.writable) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> IOException(<span class="string">"Channel not open for writing - cannot extend file to required size"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">while</span>(<span class="keyword">true</span>) &#123;</span><br><span class="line">                        var12 = <span class="keyword">this</span>.nd.truncate(<span class="keyword">this</span>.fd, var2 + var4);</span><br><span class="line">                        <span class="keyword">if</span> (var12 != -<span class="number">3</span> || !<span class="keyword">this</span>.isOpen()) &#123;</span><br><span class="line">                            <span class="keyword">if</span> (!<span class="keyword">this</span>.isOpen()) &#123;</span><br><span class="line">                                var13 = <span class="keyword">null</span>;</span><br><span class="line">                                <span class="keyword">return</span> var13;</span><br><span class="line">                            &#125;</span><br><span class="line">                            <span class="keyword">break</span>;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (var4 != <span class="number">0L</span>) &#123;</span><br><span class="line">                    var12 = (<span class="keyword">int</span>)(var2 % allocationGranularity);</span><br><span class="line">                    <span class="keyword">long</span> var34 = var2 - (<span class="keyword">long</span>)var12;</span><br><span class="line">                    <span class="keyword">long</span> var15 = var4 + (<span class="keyword">long</span>)var12;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        var7 = <span class="keyword">this</span>.map0(var6, var34, var15);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (OutOfMemoryError var30) &#123;</span><br><span class="line">                        System.gc();</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            Thread.sleep(<span class="number">100L</span>);</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (InterruptedException var29) &#123;</span><br><span class="line">                            Thread.currentThread().interrupt();</span><br><span class="line">                        &#125;</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            var7 = <span class="keyword">this</span>.map0(var6, var34, var15);</span><br><span class="line">                        &#125; <span class="keyword">catch</span> (OutOfMemoryError var28) &#123;</span><br><span class="line">                            <span class="keyword">throw</span> <span class="keyword">new</span> IOException(<span class="string">"Map failed"</span>, var28);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    FileDescriptor var17;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        var17 = <span class="keyword">this</span>.nd.duplicateForMapping(<span class="keyword">this</span>.fd);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (IOException var27) &#123;</span><br><span class="line">                        unmap0(var7, var15);</span><br><span class="line">                        <span class="keyword">throw</span> var27;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">assert</span> IOStatus.checkAll(var7);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">assert</span> var7 % allocationGranularity == <span class="number">0L</span>;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">int</span> var18 = (<span class="keyword">int</span>)var4;</span><br><span class="line">                    FileChannelImpl.Unmapper var19 = <span class="keyword">new</span> FileChannelImpl.Unmapper(var7, var15, var18, var17);</span><br><span class="line">                    MappedByteBuffer var20;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.writable &amp;&amp; var6 != <span class="number">0</span>) &#123;</span><br><span class="line">                        var20 = Util.newMappedByteBuffer(var18, var7 + (<span class="keyword">long</span>)var12, var17, var19);</span><br><span class="line">                        <span class="keyword">return</span> var20;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    var20 = Util.newMappedByteBufferR(var18, var7 + (<span class="keyword">long</span>)var12, var17, var19);</span><br><span class="line">                    <span class="keyword">return</span> var20;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                var7 = <span class="number">0L</span>;</span><br><span class="line">                var33 = <span class="keyword">new</span> FileDescriptor();</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">this</span>.writable &amp;&amp; var6 != <span class="number">0</span>) &#123;</span><br><span class="line">                    var13 = Util.newMappedByteBuffer(<span class="number">0</span>, <span class="number">0L</span>, var33, (Runnable)<span class="keyword">null</span>);</span><br><span class="line">                    <span class="keyword">return</span> var13;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                var13 = Util.newMappedByteBufferR(<span class="number">0</span>, <span class="number">0L</span>, var33, (Runnable)<span class="keyword">null</span>);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">this</span>.threads.remove(var9);</span><br><span class="line">                <span class="keyword">this</span>.end(IOStatus.checkAll(var7));</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> var13;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/NIO/" rel="tag"># NIO</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/07/PlayFramework之一：搭建开发环境/" rel="next" title="PlayFramework之一：搭建开发环境">
                <i class="fa fa-chevron-left"></i> PlayFramework之一：搭建开发环境
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/09/JVM-TLAB之逃逸分析/" rel="prev" title="JVM-TLAB之逃逸分析">
                JVM-TLAB之逃逸分析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#文件通道"><span class="nav-number">1.</span> <span class="nav-text">文件通道</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内存映射文件"><span class="nav-number">2.</span> <span class="nav-text">内存映射文件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是内存映射文件"><span class="nav-number">2.0.1.</span> <span class="nav-text">什么是内存映射文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#为什么使用内存映射文件"><span class="nav-number">2.0.2.</span> <span class="nav-text">为什么使用内存映射文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#如何使用内存映射文件"><span class="nav-number">2.0.3.</span> <span class="nav-text">如何使用内存映射文件</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
